package com.pain.scaffold.common.utils;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.pain.scaffold.common.exception.ServiceException;

import java.util.HashMap;
import java.util.Map;

/**
 * 地址查询工具类
 * 高德开放API：https://lbs.amap.com/api/webservice/guide/api/georegeo
 */
public class AddressUtils {
    public static void main(String[] args) {
        String address = "新疆维吾尔自治区省乌鲁木齐市市区沙依巴克区乌鲁木齐市沙依巴克区钱塘江路419号喀什国际酒店";
        Map<String, Object> body = new HashMap<>(3);
        body.put("key","5164cf9e7a811d6ca5b46aaa701c4446");
        body.put("coordsys","gps");
        body.put("address",address);
        String get = HttpUtil.get("https://restapi.amap.com/v3/geocode/geo",body);
        JSONObject jsonObject = JSON.parseObject(get);
        if(!jsonObject.get("info").equals("OK")){
            throw new ServiceException("地址解析异常");
        }
        JSONObject geocodes = (JSONObject) ((JSONArray) jsonObject.get("geocodes")).get(0);
        String province = geocodes.getString("province");
        String city = geocodes.getString("city");
        String district = geocodes.getString("district");
        String formattedAddress = geocodes.getString("formatted_address");
        int addressIndex = formattedAddress.indexOf(district);
        String detailAddress = formattedAddress.substring(addressIndex+district.length());
    }
}
